#include "widget.h"
#include "ui_widget.h"
#include "rotatedevices.h"
#include "qdebug.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowIcon(QIcon(":/img/protate.ico"));
    setWindowTitle("设备旋转平台控制端");
    setFixedSize(1650,632);
    System_Init();
    Serial_Init();
}

Widget::~Widget()
{
    delete ui;
    delete com_Timer;
    delete sysTimer;
}

void Widget::Serial_Init()
{
    com_Timer=new QTimer;
    sysTimer=new QTimer;
    ui->comport->clear();
    QList<QSerialPortInfo> availablePorts = QSerialPortInfo::availablePorts();
    QSerialPortInfo::availablePorts();
    foreach(const QSerialPortInfo &info,qAsConst(availablePorts)){
        oldPortStringList<<info.portName();
        ui->comport->addItem(info.portName());  
    }
    if(oldPortStringList.isEmpty()){
        updateLabel(ui->status,"","");
        updateLabel(ui->connected_status,"无可用串口","black");
    }
    else{
        updateLabel(ui->connected_status,"串口状态>>","red");
        updateLabel(ui->status,ui->comport->currentText()+" CLOSED","red");
    }
    connect(com_Timer,&QTimer::timeout,this,&Widget::updateSerialPort);
    connect(sysTimer,&QTimer::timeout,this,&Widget::updateSystemTime);
    connect(&globalPort,&QSerialPort::readyRead,this,&Widget::portRecvData);
    connect(&globalPort,&QSerialPort::errorOccurred,this,&Widget::handleSerialerrs);
    com_Timer->start(1000);
    sysTimer->start(1000);
}

void Widget::System_Init()
{
    sendpackage.datapack[0].address=DEVICE1_ADDR;
    sendpackage.datapack[1].address=DEVICE2_ADDR;
    sendpackage.datapack[2].address=DEVICE3_ADDR;
    sendpackage.datapack[3].address=DEVICE4_ADDR;

    QIntValidator va(-360,360,this);
    setupInputField(ui->userinput1, &va, 18);
    setupInputField(ui->userinput2, &va, 4);
    setupInputField(ui->userinput3, &va, 4);
    setupInputField(ui->userinput4, &va, 4);

    setupLcdNumber(ui->lcdNumber,4);
    setupLcdNumber(ui->lcdNumber_2,4);
    setupLcdNumber(ui->lcdNumber_3,4);
    setupLcdNumber(ui->lcdNumber_4,4);

    ui->spinBox->setEnabled(false);

    connect(ui->checkBox,&QCheckBox::stateChanged,this,&Widget::onCheckBoxStateChanged);  
    connect(ui->btn_open_serial,&QPushButton::clicked,this,&Widget::Control_port);
    connect(ui->btn_clear,&QPushButton::clicked,this,&Widget::Clear);
    connect(ui->btn_send_degree,&QPushButton::clicked,this,&Widget::Send_all_data2Serial);
    connect(ui->btn_device_1,&QPushButton::clicked,this,&Widget::Device1_zeroSetting);
    connect(ui->btn_device_2,&QPushButton::clicked,this,&Widget::Device2_zeroSetting);
    connect(ui->btn_device_3,&QPushButton::clicked,this,&Widget::Device3_zeroSetting);
    connect(ui->btn_device_4,&QPushButton::clicked,this,&Widget::Device4_zeroSetting);
    connect(ui->btn_save_log,&QPushButton::clicked,this,&Widget::Savelog);
    connect(ui->btn_all_device0,&QPushButton::clicked,this,&Widget::DeviceAll_zeroSetting);
}

void Widget::Control_port()
{
    com_Timer->stop();
    if(ui->btn_open_serial->text()=="打开串口")
    {
        globalPort.setPortName(ui->comport->currentText());
        globalPort.setBaudRate(ui->bd->currentText().toInt());
        switch (ui->databit->currentText().toInt()) {
            case 8:globalPort.setDataBits(QSerialPort::Data8);break;
            case 7:globalPort.setDataBits(QSerialPort::Data7);break;
            case 6:globalPort.setDataBits(QSerialPort::Data6);break;
            default:globalPort.setDataBits(QSerialPort::Data5);break;
        }
        switch (ui->checkbit->currentIndex()) {
            case 0:globalPort.setParity(QSerialPort::NoParity);break;
            case 1:globalPort.setParity(QSerialPort::OddParity);break;
            default:globalPort.setParity(QSerialPort::EvenParity);break;
        }
        switch (ui->stopbit->currentIndex()) {
            case 0:globalPort.setStopBits(QSerialPort::OneStop);break;
            default:globalPort.setStopBits(QSerialPort::TwoStop);break;
       }
       if(globalPort.open(QIODevice::ReadWrite)){
           check=true;
           ui->btn_send_degree->click();
           ui->btn_open_serial->setText("关闭串口");
           updateLabel(ui->connected_status,"串口状态>>","green");
           updateLabel(ui->status,globalPort.portName()+" OPENNED","green");
           ui->userinput1->setEnabled(!globalCheckBoxState);
           ui->userinput2->setEnabled(!globalCheckBoxState);
           ui->userinput3->setEnabled(!globalCheckBoxState);
           ui->userinput4->setEnabled(!globalCheckBoxState);
           ui->comport->setEnabled(false);
           ui->bd->setEnabled(false);
           ui->databit->setEnabled(false);
           ui->checkbit->setEnabled(false);
           ui->stopbit->setEnabled(false);
       }
    }
    else if(ui->btn_open_serial->text()=="关闭串口"){
        check=false;
        com_Timer->start(1000);
        globalPort.close();
        updateLabel(ui->connected_status,"串口状态>>","red");
        updateLabel(ui->status,globalPort.portName()+" CLOSED","red");
        ui->comport->setEnabled(true);
        ui->bd->setEnabled(true);
        ui->databit->setEnabled(true);
        ui->checkbit->setEnabled(true);
        ui->stopbit->setEnabled(true);
        ui->btn_open_serial->setText("打开串口");
    }
}

void Widget::Clear()
{
    ui->userinput1->clear();
    ui->userinput2->clear();
    ui->userinput3->clear();
    ui->userinput4->clear();
    ui->textBrowser->clear();
}

void Widget::Send_all_data2Serial()
{
    if(check){
        if(globalCheckBoxState){
            int step=ui->spinBox->value();
            cur_degree1=cur_degree1+step;
            cur_degree2=cur_degree2+step;
            cur_degree3=cur_degree3+step;
            cur_degree4=cur_degree4+step;

            sendpackage.datapack[0].data[0] = (step>>8)&0xFF;
            sendpackage.datapack[0].data[1] = (step)&0xFF;

            sendpackage.datapack[1].data[0] = (step>>8)&0xFF;
            sendpackage.datapack[1].data[1] = (step)&0xFF;

            sendpackage.datapack[2].data[0] = (step>>8)&0xFF;
            sendpackage.datapack[2].data[1] = (step)&0xFF;

            sendpackage.datapack[3].data[0] = (step>>8)&0xFF;
            sendpackage.datapack[3].data[1] = (step)&0xFF;

            if(cur_degree1>=360) cur_degree1=cur_degree1%360;
            if(cur_degree2>=360) cur_degree2=cur_degree2%360;
            if(cur_degree3>=360) cur_degree3=cur_degree3%360;
            if(cur_degree4>=360) cur_degree4=cur_degree4%360;

            QByteArray send_data(reinterpret_cast<char*>(&sendpackage), sizeof(sendpackage));
            globalPort.write(send_data);      
        }
        else{
            int degree1=ui->userinput1->text().toInt();
            int degree2=ui->userinput2->text().toInt();
            int degree3=ui->userinput3->text().toInt();
            int degree4=ui->userinput4->text().toInt();
            cur_degree1=cur_degree1+degree1;
            cur_degree2=cur_degree2+degree2;
            cur_degree3=cur_degree3+degree3;
            cur_degree4=cur_degree4+degree4;

            sendpackage.datapack[0].data[0] = (degree1>>8)&0xFF;
            sendpackage.datapack[0].data[1] = (degree1)&0xFF;

            sendpackage.datapack[1].data[0] = (degree2>>8)&0xFF;
            sendpackage.datapack[1].data[1] = (degree2)&0xFF;

            sendpackage.datapack[2].data[0] = (degree3>>8)&0xFF;
            sendpackage.datapack[2].data[1] = (degree3)&0xFF;

            sendpackage.datapack[3].data[0] = (degree4>>8)&0xFF;
            sendpackage.datapack[3].data[1] = (degree4)&0xFF;

            if(cur_degree1>=360) cur_degree1=cur_degree1%360;
            if(cur_degree2>=360) cur_degree2=cur_degree2%360;
            if(cur_degree3>=360) cur_degree3=cur_degree3%360;
            if(cur_degree4>=360) cur_degree4=cur_degree4%360;

            QByteArray send_data(reinterpret_cast<char*>(&sendpackage), sizeof(sendpackage));
            globalPort.write(send_data);
        }
        ui->device1->setPlatform_Angle(cur_degree1);
        ui->device2->setPlatform_Angle(cur_degree2);
        ui->device3->setPlatform_Angle(cur_degree3);
        ui->device4->setPlatform_Angle(cur_degree4);
    }

    ui->lcdNumber->display(cur_degree1);
    ui->lcdNumber_2->display(cur_degree2);
    ui->lcdNumber_3->display(cur_degree3);
    ui->lcdNumber_4->display(cur_degree4);
}

void Widget::Device1_zeroSetting()
{
    if(check){
        cur_degree1=0;
        sendpackage.datapack[0].data[0] = 0xFF;
        sendpackage.datapack[0].data[1] = 0x0F;

        sendpackage.datapack[1].data[0] = 0;
        sendpackage.datapack[1].data[1] = 0;

        sendpackage.datapack[2].data[0] = 0;
        sendpackage.datapack[2].data[1] = 0;

        sendpackage.datapack[3].data[0] = 0;
        sendpackage.datapack[3].data[1] = 0;

        QByteArray send_data(reinterpret_cast<char*>(&sendpackage), sizeof(sendpackage));
        globalPort.write(send_data);
        ui->device1->setPlatform_Angle(cur_degree1);
   }
     ui->lcdNumber->display(cur_degree1);
     ui->userinput1->clear();
}

void Widget::Device2_zeroSetting()
{
    if(check){
      cur_degree2=0;
      sendpackage.datapack[0].data[0] = 0;
      sendpackage.datapack[0].data[1] = 0;
      sendpackage.datapack[1].data[0] = 0xFF;
      sendpackage.datapack[1].data[1] = 0x0F;
      sendpackage.datapack[2].data[0] = 0;
      sendpackage.datapack[2].data[1] = 0;
      sendpackage.datapack[3].data[0] = 0;
      sendpackage.datapack[3].data[1] = 0;

      QByteArray send_data(reinterpret_cast<char*>(&sendpackage), sizeof(sendpackage));
      globalPort.write(send_data);
      ui->device2->setPlatform_Angle(cur_degree2);
   }
   ui->lcdNumber_2->display(cur_degree2);
   ui->userinput2->clear();
}

void Widget::Device3_zeroSetting()
{
    if(check){
        cur_degree3=0;
        sendpackage.datapack[0].data[0] = 0;
        sendpackage.datapack[0].data[1] = 0;
        sendpackage.datapack[1].data[0] = 0;
        sendpackage.datapack[1].data[1] = 0;
        sendpackage.datapack[2].data[0] = 0xFF;
        sendpackage.datapack[2].data[1] = 0x0F;
        sendpackage.datapack[3].data[0] = 0;
        sendpackage.datapack[3].data[1] = 0;

        QByteArray send_data(reinterpret_cast<char*>(&sendpackage), sizeof(sendpackage));
        globalPort.write(send_data);
        ui->device3->setPlatform_Angle(cur_degree3);
    }
    ui->lcdNumber_3->display(cur_degree3);
    ui->userinput3->clear();
}

void Widget::Device4_zeroSetting()
{
    if(check){
        cur_degree4=0;
        sendpackage.datapack[0].data[0] = 0;
        sendpackage.datapack[0].data[1] = 0;
        sendpackage.datapack[1].data[0] = 0;
        sendpackage.datapack[1].data[1] = 0;
        sendpackage.datapack[2].data[0] = 0;
        sendpackage.datapack[2].data[1] = 0;
        sendpackage.datapack[3].data[0] = 0xFF;
        sendpackage.datapack[3].data[1] = 0x0F;
        QByteArray send_data(reinterpret_cast<char*>(&sendpackage), sizeof(sendpackage));
        globalPort.write(send_data);
        ui->device4->setPlatform_Angle(cur_degree4);
    }
    ui->lcdNumber_4->display(cur_degree4);
    ui->userinput4->clear();
}

void Widget::DeviceAll_zeroSetting()
{
    if(check){
        cur_degree1=0;
        cur_degree2=0;
        cur_degree3=0;
        cur_degree4=0;
        sendpackage.datapack[0].data[0] = 0xFF;
        sendpackage.datapack[0].data[1] = 0x0F;

        sendpackage.datapack[1].data[0] = 0xFF;
        sendpackage.datapack[1].data[1] = 0x0F;

        sendpackage.datapack[2].data[0] = 0xFF;
        sendpackage.datapack[2].data[1] = 0x0F;

        sendpackage.datapack[3].data[0] = 0xFF;
        sendpackage.datapack[3].data[1] = 0x0F;

        QByteArray send_data(reinterpret_cast<char*>(&sendpackage), sizeof(sendpackage));
        globalPort.write(send_data);

        ui->device1->setPlatform_Angle(cur_degree1);
        ui->device2->setPlatform_Angle(cur_degree2);
        ui->device3->setPlatform_Angle(cur_degree3);
        ui->device4->setPlatform_Angle(cur_degree4);
    }
    ui->lcdNumber->display(cur_degree1);
    ui->lcdNumber_2->display(cur_degree2);
    ui->lcdNumber_3->display(cur_degree3);
    ui->lcdNumber_4->display(cur_degree4);

    ui->userinput1->clear();
    ui->userinput2->clear();
    ui->userinput3->clear();
    ui->userinput4->clear();
}

void Widget::onCheckBoxStateChanged(int state)
{
    if(state==Qt::Checked){
        globalCheckBoxState = true;
        ui->spinBox->setEnabled(true);
        ui->userinput1->setEnabled(false);
        ui->userinput2->setEnabled(false);
        ui->userinput3->setEnabled(false);
        ui->userinput4->setEnabled(false);
    }
    else{
        globalCheckBoxState = false;
        ui->spinBox->setEnabled(false);
        ui->userinput1->setEnabled(true);
        ui->userinput2->setEnabled(true);
        ui->userinput3->setEnabled(true);
        ui->userinput4->setEnabled(true);
    }
}

void Widget::portRecvData()
{
    QByteArray buffer;
    QByteArray MyComRevBUff;
    QString StrTemp;
    MyComRevBUff = globalPort.readAll();
    buffer.append(MyComRevBUff);
    // ui->textBrowser->insertPlainText(QString::fromLocal8Bit(MyComRevBUff));
    // ui->textBrowser->moveCursor(QTextCursor::End);
    // qDebug()<<MyComRevBUff;
    while (!buffer.isEmpty()) {
        int headIndex = buffer.indexOf("\x5A\xA5");
        int tailIndex=0;
        if(headIndex==-1){
            buffer.clear();
            return;
        }
        if(buffer.mid(headIndex+19,1)=="\x8A"){//找到帧尾
            tailIndex=headIndex+19;
            QByteArray validData = buffer.mid(headIndex+3, 16);
            StrTemp = QString::fromLocal8Bit(validData);
            StrTemp = validData.toHex().toUpper();
            logData(buffer.mid(headIndex, 20),logType::Type_Received);
            int D1C1_index =StrTemp.indexOf("D1C1");
            if (D1C1_index != -1) {
                 QVector<int> all_value=convertGroups(StrTemp);
                 if (all_value[0] != 65295){
                     ui->D1_Motor_return->setText(QString("%1°").arg(all_value[0]));
                     ui->lcdNumber->display(all_value[0]);
                     cur_degree1=all_value[0];
                     ui->device1->setPlatform_Angle(cur_degree1);
                 }
                 if (all_value[1] != 65295)ui->label_D1degree->setText(QString("%1°").arg(all_value[1]));
                 if (all_value[2] != 65295)ui->label_D1ABdegree->setText(QString("%1°").arg(all_value[2]));
                 if (all_value[3] != 65295)ui->label_D1distance->setText(QString("%1m").arg(all_value[3]));
            }

            int D2C2_index =StrTemp.indexOf("D2C2");
            if (D2C2_index != -1) {
                 QVector<int> all_value=convertGroups(StrTemp);
                 if (all_value[0] != 65295){
                     ui->D2_Motor_return->setText(QString("%1°").arg(all_value[0]));
                     ui->lcdNumber_2->display(all_value[0]);
                     cur_degree2=all_value[0];
                     ui->device2->setPlatform_Angle(cur_degree2);
                 }
                 if (all_value[1] != 65295) ui->label_D2degree->setText(QString("%1°").arg(all_value[1]));
                 if (all_value[2] != 65295) ui->label_D2ABdegree->setText(QString("%1°").arg(all_value[2]));
                 if (all_value[3] != 65295) ui->label_D2distance->setText(QString("%1m").arg(all_value[3]));
            }

            int D3C3_index =StrTemp.indexOf("D3C3");
            if (D3C3_index != -1) {
                 QVector<int> all_value=convertGroups(StrTemp);
                 if (all_value[0] != 65295){
                     ui->D3_Motor_return->setText(QString("%1°").arg(all_value[0]));
                     ui->lcdNumber_3->display(all_value[0]);
                     cur_degree3=all_value[0];
                     ui->device3->setPlatform_Angle(cur_degree3);
                 }
                 if (all_value[1] != 65295) ui->label_D3degree->setText(QString("%1°").arg(all_value[1]));
                 if (all_value[2] != 65295) ui->label_D3ABdegree->setText(QString("%1°").arg(all_value[2]));
                 if (all_value[3] != 65295) ui->label_D3distance->setText(QString("%1m").arg(all_value[3]));
            }

            int D4C4_index =StrTemp.indexOf("D4C4");
            if (D4C4_index != -1) {
                QVector<int> all_value=convertGroups(StrTemp);
                if (all_value[0] != 65295){
                     ui->D4_Motor_return->setText(QString("%1°").arg(all_value[0]));
                     ui->lcdNumber_4->display(all_value[0]);
                     cur_degree4=all_value[0];
                     ui->device4->setPlatform_Angle(cur_degree4);
                }
                if (all_value[1] != 65295) ui->label_D4degree->setText(QString("%1°").arg(all_value[1]));
                if (all_value[2] != 65295) ui->label_D4ABdegree->setText(QString("%1°").arg(all_value[2]));
                if (all_value[3] != 65295) ui->label_D4distance->setText(QString("%1m").arg(all_value[3]));
            }
        }
        buffer.remove(0,tailIndex+1);
    }
}

QVector<int> Widget::convertGroups(const QString &str)
{
    QVector<int> results;
    int value;
    for(int i=4;i<str.length();i+=8)
    {
       value=0;
       QString data = str.mid(i, 4);
       QByteArray byteArray = QByteArray::fromHex(data.toLatin1());
       for (int j = 0; j < byteArray.size(); ++j) {
           value = (value << 8) | static_cast<unsigned char>(byteArray[j]);
       }
       results.append(value);
    }
    return results;
}

void Widget::on_device1_changeDegree_clicked()
{
    if(check){
        int degree1=ui->userinput1->text().toInt();
        cur_degree1=cur_degree1+degree1;

        sendpackage.datapack[0].data[0] = (cur_degree1>>8)&0xFF;
        sendpackage.datapack[0].data[1] = (cur_degree1)&0xFF;

        sendpackage.datapack[1].data[0] = 0;
        sendpackage.datapack[1].data[1] = 0;

        sendpackage.datapack[2].data[0] = 0;
        sendpackage.datapack[2].data[1] = 0;

        sendpackage.datapack[3].data[0] = 0;
        sendpackage.datapack[3].data[1] = 0;

        QByteArray send_data(reinterpret_cast<char*>(&sendpackage), sizeof(sendpackage));
        globalPort.write(send_data);
        logData(send_data,logType::Type_Send);
        ui->device1->setPlatform_Angle(cur_degree1);
        if(cur_degree1>=360) cur_degree1=cur_degree1%360;
    }
    ui->lcdNumber->display(cur_degree1);

}

void Widget::on_device2_changeDegree_clicked()
{
    if(check){
        int degree2=ui->userinput2->text().toInt();
        cur_degree2=cur_degree2+degree2;

        sendpackage.datapack[0].data[0] = 0;
        sendpackage.datapack[0].data[1] = 0;

        sendpackage.datapack[1].data[0] = (cur_degree2>>8)&0xFF;
        sendpackage.datapack[1].data[1] = (cur_degree2)&0xFF;

        sendpackage.datapack[2].data[0] = 0;
        sendpackage.datapack[2].data[1] = 0;

        sendpackage.datapack[3].data[0] = 0;
        sendpackage.datapack[3].data[1] = 0;

        QByteArray send_data(reinterpret_cast<char*>(&sendpackage), sizeof(sendpackage));
        globalPort.write(send_data);
        ui->device2->setPlatform_Angle(cur_degree2);
        if(cur_degree2>=360) cur_degree2=cur_degree2%360;
    }
    ui->lcdNumber_2->display(cur_degree2);
}

void Widget::on_device3_changeDegree_clicked()
{
    if(check){
        int degree3=ui->userinput3->text().toInt();
        cur_degree3=cur_degree3+degree3;

        sendpackage.datapack[0].data[0] = 0;
        sendpackage.datapack[0].data[1] = 0;

        sendpackage.datapack[1].data[0] = 0;
        sendpackage.datapack[1].data[1] = 0;

        sendpackage.datapack[2].data[0] = (cur_degree3>>8)&0xFF;
        sendpackage.datapack[2].data[1] = (cur_degree3)&0xFF;

        sendpackage.datapack[3].data[0] = 0;
        sendpackage.datapack[3].data[1] = 0;

        QByteArray send_data(reinterpret_cast<char*>(&sendpackage), sizeof(sendpackage));
        globalPort.write(send_data);
        ui->device3->setPlatform_Angle(cur_degree3);
        if(cur_degree3>=360) cur_degree3=cur_degree3%360;
    }
    ui->lcdNumber_3->display(cur_degree3);
}

void Widget::on_device4_changeDegree_clicked()
{
    if(check){
        int degree4=ui->userinput4->text().toInt();
        cur_degree4=cur_degree4+degree4;

        sendpackage.datapack[0].data[0] = 0;
        sendpackage.datapack[0].data[1] = 0;

        sendpackage.datapack[1].data[0] = 0;
        sendpackage.datapack[1].data[1] = 0;

        sendpackage.datapack[2].data[0] = 0;
        sendpackage.datapack[2].data[1] = 0;

        sendpackage.datapack[3].data[0] = (cur_degree4>>8)&0xFF;
        sendpackage.datapack[3].data[1] = (cur_degree4)&0xFF;

        QByteArray send_data(reinterpret_cast<char*>(&sendpackage), sizeof(sendpackage));
        globalPort.write(send_data);
        ui->device4->setPlatform_Angle(cur_degree4);
        if(cur_degree4>=360) cur_degree4=cur_degree4%360;
    }
    ui->lcdNumber_4->display(cur_degree4);
}

void Widget::updateSerialPort()
{
    QStringList newPortStringList;
    QList<QSerialPortInfo> availablePorts = QSerialPortInfo::availablePorts();
    for(const QSerialPortInfo &info:qAsConst(availablePorts))
    {
        newPortStringList += info.portName();
    }
    if(newPortStringList.isEmpty()){
        ui->comport->clear();
        updateLabel(ui->status,"","");
        updateLabel(ui->connected_status,"无可用串口","black");
    }
    else{
        ui->comport->clear();
        oldPortStringList=newPortStringList;
        ui->comport->addItems(oldPortStringList);
        updateLabel(ui->connected_status,"串口状态>>","red");
        updateLabel(ui->status,ui->comport->currentText()+" CLOSED","red");
    }
}

void Widget::handleSerialerrs(QSerialPort::SerialPortError error)
{
    // qDebug()<<error;
    switch (error) {
    case QSerialPort::PermissionError:
        check=false;
        globalPort.close();
        com_Timer->start(1000);
        ui->comport->clear();
        ui->btn_open_serial->setText("打开串口");
        ui->comport->setEnabled(true);
        ui->bd->setEnabled(true);
        ui->databit->setEnabled(true);
        ui->checkbit->setEnabled(true);
        ui->stopbit->setEnabled(true);
        updateLabel(ui->status,"","");
        updateLabel(ui->connected_status,"串口断开>>","yellow");
        break;
    case QSerialPort::DeviceNotFoundError:
        com_Timer->start(1000);
        updateLabel(ui->status,"","");
        updateLabel(ui->connected_status,"无可用串口","blue");
        ui->comport->setEnabled(true);
        ui->bd->setEnabled(true);
        ui->databit->setEnabled(true);
        ui->checkbit->setEnabled(true);
        ui->stopbit->setEnabled(true);
        break;
    default:case QSerialPort::NoError:
        break;
    }
}

void Widget::updateSystemTime()
{
    QString formattedDateTime = QDateTime::currentDateTime().toString("yyyy/MM/dd-HH:mm:ss");
    QString dayOfWeek = QDate::currentDate().toString("dddd");
    ui->SystemTime->setText(formattedDateTime+" "+dayOfWeek);
}

void Widget::logData(const QByteArray &data, logType Type)
{
    QString timestamp = QDateTime::currentDateTime().toString("yyyy-MM-dd hh:mm:ss");
    QString logMessage;
    switch (Type) {
        case Type_Send:
        default:logMessage = QString("[%1]>>>%2: %3")
                             .arg(timestamp,Type == Type_Send ? "Sent" : "Received",QString(data.toHex().toUpper()));
            break;
    }
    ui->textBrowser->append(logMessage);
}

void Widget::updateLabel(QLabel *label, const QString &text, const QString &color)
{
    label->setText(text);
    label->setStyleSheet("color:" + color);
}

void Widget::setupInputField(QLineEdit *inputField, QValidator *validator, int maxLength) {
    inputField->setValidator(validator);
    inputField->setMaxLength(maxLength);
}

void Widget::setupLcdNumber(QLCDNumber *lcdNumber,int digitCount) {
    lcdNumber->setDigitCount(digitCount);
    lcdNumber->setMode(QLCDNumber::Dec);
    lcdNumber->setSegmentStyle(QLCDNumber::Flat);
}

void Widget::Savelog()
{
    QString content = ui->textBrowser->toPlainText();
    if(content.isEmpty()){
        QMessageBox::warning(nullptr, "保存提示", "文本框为空，无需保存！");
        return;
    }
    QString desktopPath = QStandardPaths::writableLocation(QStandardPaths::DesktopLocation);
    QString fileName = QString("log_%1.txt").arg(QDateTime::currentDateTime().toString("yyyyMMdd_hhmmss"));
    QString filePath = desktopPath + "/" + fileName;
    QFile file(filePath);
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        QMessageBox::warning(nullptr, "保存错误", "无法打开文件进行写入！");
        return;
    }
    QTextStream out(&file);
    out << content;
    file.close();
    QMessageBox::information(nullptr, "保存成功", QString("内容已成功保存到 %1").arg(filePath));
}
